package felix.rule.service.impl.install;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.DriverManager;

@Service
@Profile("install")
@Slf4j
public class SqlDatabaseInstallService {

    @Value("${spring.datasource.url}")
    protected String dbUrl;

    @Value("${spring.datasource.username}")
    protected String dbUserName;

    @Value("${spring.datasource.password}")
    protected String dbPassword;

    private static final String SQL_DIR = "sql";

    public void loadSql(String fileName) throws Exception {
        InputStream is = getClass().getClassLoader().getResourceAsStream(SQL_DIR + "/" + fileName);
        if (is == null) {
            throw new RuntimeException("Not fileNmae in resource :" + SQL_DIR + "/" + fileName);
        }
        ByteArrayOutputStream result = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length;
        while ((length = is.read(buffer)) != -1) {
            result.write(buffer, 0, length);
        }
        String sql = result.toString(StandardCharsets.UTF_8.name());
        try (Connection conn = DriverManager.getConnection(dbUrl, dbUserName, dbPassword)) {
            conn.createStatement().execute(sql);
        }
    }

}
